import Cookies from 'js-cookie';

import { tokenHeader } from '@/config';
import { getItem, TENANT_ID, ACCESS_TOKEN, setItem, REFRESH_TOKEN, USER_INFO, removeItem } from '@/utils/db';
import { validatenull } from './validate';

const TokenKey = 'saber-access-token';
const RefreshTokenKey = 'saber-refresh-token';

export function getToken() {
  return Cookies.get(TokenKey);
}

export function setToken(token: string) {
  setItem(ACCESS_TOKEN, token);
  return Cookies.set(TokenKey, token);
}

export function getRefreshToken() {
  return Cookies.get(RefreshTokenKey);
}

export function setRefreshToken(token: string) {
  setItem(REFRESH_TOKEN, token);
  return Cookies.set(RefreshTokenKey, token);
}

export function removeToken() {
  return Cookies.remove(TokenKey);
}

export function removeRefreshToken() {
  return Cookies.remove(RefreshTokenKey);
}

export const headers = {
  'tenant-id': getItem(TENANT_ID),
  [tokenHeader]: 'bearer ' + getItem(ACCESS_TOKEN),
};

export const clearCache = () => {
  removeItem(USER_INFO);
  removeItem(ACCESS_TOKEN);
  removeItem(REFRESH_TOKEN);
  removeToken();
  removeRefreshToken();
};

export const hasLogin = () => {
  const userInfo = getItem(USER_INFO) || {};
  const result = !validatenull(userInfo.account);
  return result;
};

export const isAuth = (id: number, routes: number[] = []) => {
  return routes.includes(id);
};

export const user = () => {
  return getItem(USER_INFO);
};
